package action;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *该类有三个作用：
 *	1. 生成验证码图片
 *	2. 将验证码绑定到session对象上
 *	3. 将验证码图片发送到前台页面 
 */
@SuppressWarnings("serial")
public class CheckCodeServlet extends HttpServlet {
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//生成一个随机数
		String number = getNumber(4);
		//将随机数绑定到session对象上
		HttpSession session = request.getSession();
		session.setAttribute("checkcode", number);
		//生成一张图片，该图片包含了这个随机数
		//step1 创建一个内存映像对象
		BufferedImage image = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
		//step2 得到画笔
		Graphics g = image.getGraphics();
		//step3 给画布填充颜色
		Random rand = new Random();
		g.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
		g.fillRect(0, 0, 100, 30);
		//step4 绘画
		g.setColor(new Color(0, 0, 0));
		g.drawString(number, 17, 20);
		//step5 加一些干扰线
		for (int i = 0; i < 6; i++) {
			g.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
			g.drawLine(rand.nextInt(100), rand.nextInt(30), rand.nextInt(100), rand.nextInt(30));
		}
		//压缩图片，发送给浏览器
		response.setContentType("image/jpeg");
		OutputStream out = response.getOutputStream();
		//write方法会将image对象包含的数据按指定的算法进行压缩，然后输出到指定的流
		javax.imageio.ImageIO.write(image, "jpeg", out);
	}
	
	/**
	 * 返回一个长度为size，并且由A~Z、0~9中的字符组成的字符串
	 * @param size
	 * @return
	 */
	private String getNumber(int size){
		char[] chars = {'A','B','C','D','E','F','G','H','I','J','K',
				'L','M','N','O','P','Q','R','S','T','U','V','W',
				'X','Y','Z','0','1','2','3','4','5','6','7','8','9'};
		String result = "";
		Random rand = new Random();
		for(int i = 0; i < size; i++){
			result += chars[rand.nextInt(chars.length)];
		}
		return result;
	}
}
